<?php

namespace app\service\tool;

use app\models\cacheModel\SettingModel;
use GuzzleHttp\Utils;
use yii\base\Model;
use yii\helpers\Html;

/**
 * 请求工具类
 * Class GenerateService
 * @package app\models
 */
class RequestService extends Model
{

    /**
     * 获取：客户端[IP]地址
     * @return string
     * PS: YII自带IP获取会是最后一跳这可不行呀
     */
    public static function getClientIp()
    {

        if (getenv('HTTP_CLIENT_IP')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } else if (getenv('HTTP_X_FORWARDED_FOR')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('REMOTE_ADDR')) {
            $ip = getenv('REMOTE_ADDR');
        } else {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // 为啥分割？由于[REMOTE_ADDR]可能会获取出串，第一个是第一跳为百度搜索IP获取的IP地址分割下
        $ip = explode(',', $ip);
        return empty($ip[0]) ? 'unknown' : ConvertService::clearAllSpace($ip[0]);
    }

    /**
     * 给某连接添加参数
     * @param string $url
     * @param array $params
     * @return string
     */
    public static function addParams($url = '', $params = [])
    {

        // 先将连接格式化为数组
        $urlArray          = parse_url($url);
        $urlArray['query'] = empty($urlArray['query']) ? '' : $urlArray['query'];
        // 取出参数将参数以[&]分割
        $urlParStage = explode('&', $urlArray['query']);
        $stage       = []; // 公共暂存
        $urlPar      = []; // 参数[key => value]格式
        foreach ($urlParStage as $k => $v) {
            $stage             = explode('=', $v);
            $urlPar[$stage[0]] = empty($stage[1]) ? '' : $stage[1];
        }
        // 将需要添加的参数循环加入
        foreach ($params as $k => $v) {
            $urlPar[$k] = $v;
        }
        $stage = []; // 公共暂存 - 初始化
        // 将最终参数[k => v]组合为以[=]连接的一维数组
        foreach ($urlPar as $k => $v) {
            $stage[] = $k . '=' . $v;
        }
        $stage             = implode($stage, '&');
        $urlArray['query'] = $stage;
        $end               = $urlArray['scheme'] . '://' .
            $urlArray['host'] .
            $urlArray['path'] . '?' .
            $urlArray['query'];

        return $end;
    }

    /**
     * 链接里替换某些参数
     * @param $url
     * @param $currentParams
     * @return string
     */
    public static function urlCurrent($url, $currentParams)
    {

        $urlInfo = parse_url($url);
        // 确保基础路径键存在
        $urlInfo['path'] = empty($urlInfo['path']) ?
            '/' . \Yii::$app->request->pathInfo : $urlInfo['path'];
        // 确保参数键存在
        $urlInfo['query'] = empty($urlInfo['query']) ? '' : $urlInfo['query'];
        parse_str($urlInfo['query'], $queryList);
        $newParams = array_replace_recursive($currentParams, $queryList);
        $endParams = [];
        foreach ($newParams as $k => $v) {
            if (!isset($v)) continue;
            $endParams[] = $k . '=' . $v;
        }

        // 无参数
        if (empty($endParams)) {
            return $urlInfo['path'];
        }

        // 有参数
        return $urlInfo['path'] . '?' . implode($endParams, '&');
    }

    /**
     * 检测连接是否站外链接
     * @param string $url 连接
     * @return bool
     */
    public static function urlIsOutSite($url)
    {

        // 自身域名
        $siteHost = $_SERVER['HTTP_HOST'];

        // 参数域名
        $pathInfo  = parse_url($url);
        $paramHost = empty($pathInfo['host']) ? '' : $pathInfo['host'];
        $paramHost .= empty($pathInfo['port']) ? '' : ':' . $pathInfo['port'];

        return $siteHost === $paramHost;
    }

    /**
     * 判断参数 是否为连接
     * @param $url
     * @return bool
     */
    public static function isUrl($url)
    {

        if (self::urlIsOutSite($url)) return true;
        if (filter_var($url, FILTER_VALIDATE_URL)) return true;
        if (UtilsService::cutString($url, 0, 1, '') == '/') return true;
        return false;
    }

    /**
     * 连接是否为图片
     * @param $url
     * @return bool
     */
    public static function isUrlImg($url)
    {
        $pathInfo = pathinfo($url);
        $ext      = empty($pathInfo['extension']) ? '' : $pathInfo['extension'];
        return in_array(strtolower($ext), [
            'jpg',
            'jpeg',
            'gif',
            'png',
            'bmp'
        ]);
    }
}
